use crate::gd_manager::GdManager;
use rmcp::model::{CallToolResult, Content};
use rmcp::{
    ErrorData as McpError,
    handler::server::{router::tool::ToolRouter, tool::Parameters},
    schemars, tool, tool_router,
};
use serde_json::json;
use std::sync::Arc;

#[derive(Clone)]
pub struct GdHandler {
    gd_manager: Arc<GdManager>,
    pub tool_router: ToolRouter<GdHandler>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DeviceControlParams {
    /// Control Command
    action: String,
    /// Controlled device code
    device_code: String,
}

#[tool_router]
impl GdHandler {
    pub fn new(gd_manager: Arc<GdManager>) -> Self {
        Self {
            gd_manager,
            tool_router: Self::tool_router(),
        }
    }

    #[tool(description = "Send control commands to the devices in the 3d system")]
    async fn device_control(
        &self,
        Parameters(DeviceControlParams {
            action,
            device_code,
        }): Parameters<DeviceControlParams>,
    ) -> Result<CallToolResult, McpError> {
        println!("p1: {action}");
        println!("p2: {device_code}");
        self.gd_manager
            .send(json!({
                "action": action,
                "device_code": device_code
            }))
            .await
            .unwrap();
        Ok(CallToolResult::success(vec![Content::text(
            "[FINAL] The operation is completed. The conversation ends!",
        )]))
    }
}
